﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using CustomControls;
using Model;
using DataAccess;
using Model.EntityModel;

namespace Project
{
    /// <summary>
    /// Lógica de interacción para FunctionaryRegisterContent.xaml
    /// </summary>
    public partial class FunctionaryRegisterContent : UserControl
    {
        Functionary employee = new Functionary();
        DateTime date = new DateTime();
        bool modified = false;

        public FunctionaryRegisterContent()
        {
            InitializeComponent();
            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - FunctionaryRegister");
            date = new DateTime();
            date = DateTime.Now;
            JoinDate.Content = date.ToShortDateString();
            //JoinDate.Content = date.ToString(CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
            dpBirthday.DisplayDateEnd = date.AddYears(-18);
            dpBirthday.DisplayDateStart = date.AddYears(-65);
            employee.JoinDate = date;
            tbPhone.AddValitationRule(new PhoneValidationRule());
            tbPhone.DeactivateBlankValidation();
            tbMiddleName.DeactivateBlankValidation();
            tbCI.AddValitationRule(new LenghtValidationRule(5));
            tbPasswordShowed.AddValitationRule(new LenghtValidationRule(5));
            tbPasswordShowed.CharacterCasing = CharacterCasing.Normal;
            Binding bind = new Binding();
            bind.Path = new PropertyPath("ToolTipProperty");
            bind.NotifyOnSourceUpdated = true;
            bind.ValidatesOnDataErrors = true;
            bind.Mode = BindingMode.TwoWay;
            bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            bind.ValidationRules.Clear();
            bind.ValidationRules.Add(new BlankValidRule());
            tbPassword.SetBinding(PasswordBox.ToolTipProperty, bind);
            tbPassword.DataContext = tbPassword;
            
        }
        public FunctionaryRegisterContent(long empCI)
        {
            InitializeComponent();
            groupBox3.Visibility = Visibility.Collapsed;
            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - FunctionaryRegister");
            employee = DataBaseAccess.ReadEmployee(empCI);
            dpBirthday.DisplayDateEnd = DateTime.Now.Date.AddDays(-1);
            fillInterface();
            tbPhone.AddValitationRule(new PhoneValidationRule());
            tbPhone.DeactivateBlankValidation();
            tbMiddleName.DeactivateBlankValidation();
            tbCI.AddValitationRule(new LenghtValidationRule(6));
            }

        public void fillInterface()
        {
            tbPasswordShowed.Text = "filled";
            JoinDate.Content = employee.JoinDate.ToShortDateString();
            tbAddress.Text = employee.Address;
            dpBirthday.SelectedDate = employee.BirthDate;
            tbLugarNacimiento.Text = employee.BirthPLace;
            if(employee.Phone > 0)
                tbPhone.Text = employee.Phone.ToString();
            string[] words = (employee.BloodType).Split(' ');
            cbType.SelectedValue = words[0];
            cbRH.SelectedValue = words[1];
            tbCI.Text = employee.CI.ToString();
            tbCI.IsEnabled = false;
            cbCompCivilStatus.SelectedValue = employee.CivilStatus;
             if (employee.Gener == "M")
                rbtnMale.IsChecked = true;
            else
                rbtnFemale.IsChecked = true;
            if(!String.IsNullOrEmpty(employee.MaternalName))
                tbMiddleName.Text = employee.MaternalName;
            tbName.Text = employee.Name;
            tbLastName.Text = employee.PaternalName;
            cbGrade.SelectedValue = employee.Rank;
            modified = true;
            cbCharge.SelectedValue = employee.WorkingRole;
        }

        public bool validText(string text)
        {
            if (String.IsNullOrWhiteSpace(text) || String.IsNullOrEmpty(text) || text.Length<2)
                return false;
            return true;
        }

        public bool ValidInfo()
        {
            bool res = false;
            if (!modified)
            {
                if (tbPassword.Password.Length < 5)
                {
                    Validation.MarkInvalid(tbPassword.GetBindingExpression(PasswordBox.ToolTipProperty),
                                           new ValidationError(new LenghtValidationRule(5), tbPassword));
                    tbPassword.ToolTip = "El campo debe tener al menos 5 caracteres";
                    res = true;
                }
                else
                {
                    Validation.ClearInvalid(tbPassword.GetBindingExpression(PasswordBox.ToolTipProperty));
                    tbPassword.ToolTip = null;
                }
            }
            foreach (var control in Content.Children)
            {
                GroupBox gp = control as GroupBox;
                if (gp != null)
                {
                    foreach (var ctrl in (gp.Content as Grid).Children)
                    {
                        TextBox tb = ctrl as TextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb, null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
                    }
                }
            }
            //if (validText(tbAddress.Text) && validText(tbCI.Text) && validText(tbLastName.Text) && validText(tbLugarNacimiento.Text) && validText(tbLugarNacimiento.Text) && validText(tbName.Text))
            //    if ((rbtnFemale.IsChecked == true || rbtnMale.IsChecked == true) && (rbWidow.IsChecked == true || rbDivorced.IsChecked == true || rbPartner.IsChecked == true || rbSeparated.IsChecked == true || rbMarried.IsChecked == true || rbSingle.IsChecked == true))
            //        if (cbCharge.SelectedIndex != 0 && cbGrade.SelectedIndex != 0 && cbRH.SelectedIndex != -1 && cbType.SelectedIndex != -1)
            //            if(dpBirthday.SelectedDate!=null)
            //                return true;
            return !res;
        }

        private void tbPhone_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.D0 && e.Key <= Key.D9 || e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key == Key.Delete || e.Key == Key.Back)
                e.Handled = false;
            else
                e.Handled = true;
        }

        private void tbCI_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.D0 && e.Key <= Key.D9 || e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key == Key.Delete || e.Key == Key.Back)
                e.Handled = false;
            else
                e.Handled = true;
        }

        public void fillEmployee()
        {
            employee.Address = tbAddress.Text;
            employee.BirthDate = dpBirthday.SelectedDate.Value;
            employee.BirthPLace = tbLugarNacimiento.Text;
            if (!String.IsNullOrEmpty(tbPhone.Text))
                employee.Phone = Convert.ToInt64(tbPhone.Text);
            ComboBoxItem cm=(ComboBoxItem)cbType.SelectedItem;
            ComboBoxItem sg=(ComboBoxItem)cbRH.SelectedItem;
            employee.BloodType = cm.Content.ToString() + " " + sg.Content.ToString();
            employee.CI = Convert.ToInt64(tbCI.Text);
            ComboBoxItem civ = (ComboBoxItem)cbCompCivilStatus.SelectedItem;
            employee.CivilStatus = civ.Content.ToString();
            if (rbtnMale.IsChecked == true)
                employee.Gener = "M";
            else
                employee.Gener = "F";
            if (!modified)
                employee.JoinDate = date;
            if(!String.IsNullOrEmpty(tbMiddleName.Text))
                employee.MaternalName = tbMiddleName.Text;
            employee.Name = tbName.Text;
            employee.PaternalName = tbLastName.Text;
            ComboBoxItem rank = (ComboBoxItem)cbGrade.SelectedItem;
            employee.Rank = rank.Content.ToString();
            if (modified)
                employee.Status = true;
            else
                employee.Status = false;
            ComboBoxItem charge = (ComboBoxItem)cbCharge.SelectedItem;
            employee.WorkingRole = charge.Content.ToString();
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            chkShowPass_Checked(null, null);
            chkShowPass_Unchecked(null, null);
            if (ValidInfo())
            {     
                fillEmployee();
                if (null == DataBaseAccess.ReadEmployee(employee.CI))
                {
                    if (DataBaseAccess.RegisterEmployee(employee))
                    {
                        if(!modified)
                            UserControllerAndDataAccess.RegisterUser(new Users { CiEmployee = employee.CI, Username = lblUserName.Content.ToString(), Password = tbPassword.Password, IsDirector = cbCharge.SelectedValue.ToString() == "Director", IsPsicologist = cbCharge.SelectedValue.ToString() == "Psicologo" });
                        Xceed.Wpf.Toolkit.MessageBox.Show("Funcionario guardado correctamente \n\r su usuario es: "+lblUserName.Content +"\n\ry su contraseña: " + tbPassword.Password +"\n\r tome nota!.","Exito!");
                        UIWindowManager.CleanWindow(this); 
                    }
                    else
                        Xceed.Wpf.Toolkit.MessageBox.Show("Error al Guardar","Error!",MessageBoxButton.OK,MessageBoxImage.Error);
                }

                else
                {
                    if (modified)
                    {
                        if (DataBaseAccess.UpdateEmployee(employee))
                        {
                            Xceed.Wpf.Toolkit.MessageBox.Show("Guardado correctamente");
                            UIWindowManager.CleanWindow(this);
                        }
                        else
                            Xceed.Wpf.Toolkit.MessageBox.Show("Error al Guardar");
                    }
                    else
                        Xceed.Wpf.Toolkit.MessageBox.Show("El CI ingresado ya existe");
                }
            }
            else
                Xceed.Wpf.Toolkit.MessageBox.Show("Debe llenar todos los campos marcados con asterisco");
        }

        private void tbMiddleName_TextChanged(object sender, TextChangedEventArgs e)
        {
            BuildUsername();
        }

        private void tbName_TextChanged(object sender, TextChangedEventArgs e)
        {
            BuildUsername();
        }

        private void BuildUsername()
        {
            StringBuilder strBuild = new StringBuilder("------");
            if (tbName.Text.Length > 0)
                strBuild[0] = tbName.Text[0];
            else
            {
                strBuild[0] = '-';
            }
            if (tbName.Text.Length > 1)
                strBuild[1] = tbName.Text[1];
            else
            {
                strBuild[1] = '-';
            }
            if (tbLastName.Text.Length > 0)
                strBuild[2] = tbLastName.Text[0];
            else
            {
                strBuild[2] = '-';
            }
            if (tbLastName.Text.Length > 1)
                strBuild[3] = tbLastName.Text[1];
            else
            {
                strBuild[3] = '-';
            }
            if (tbMiddleName.Text.Length > 0)
                strBuild[4] = tbMiddleName.Text[0];
            else
            {
                strBuild[4] = '-';
            }
            if (tbMiddleName.Text.Length > 1)
                strBuild[5] = tbMiddleName.Text[1];
            else
            {
                strBuild[5] = '-';
            }
            strBuild.Append(tbCI.Text);
            lblUserName.Content = strBuild.ToString().ToUpper().Trim('-');
        }

        private void tbLastName_TextChanged(object sender, TextChangedEventArgs e)
        {
            BuildUsername();
        }

        private void tbCI_TextChanged(object sender, TextChangedEventArgs e)
        {
            BuildUsername();
        }

        private void chkShowPass_Checked(object sender, RoutedEventArgs e)
        {
                tbPassword.Visibility = Visibility.Hidden;
                tbPasswordShowed.Text = tbPassword.Password;
                tbPasswordShowed.Visibility = Visibility.Visible;
                tbPasswordShowed.Text = tbPassword.Password;
        }

        private void chkShowPass_Unchecked(object sender, RoutedEventArgs e)
        {
                tbPassword.Visibility = Visibility.Visible;
                tbPasswordShowed.Visibility = Visibility.Hidden;
                tbPassword.Password = tbPasswordShowed.Text;
        }

        private void tbPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {

            if (tbPassword.Password.Length < 5)
            {
                Validation.MarkInvalid(tbPassword.GetBindingExpression(PasswordBox.ToolTipProperty),
                                       new ValidationError(new LenghtValidationRule(5), tbPassword));
                tbPassword.ToolTip = "El campo debe tener al menos 5 caracteres";
            }
            else
            {
                Validation.ClearInvalid(tbPassword.GetBindingExpression(PasswordBox.ToolTipProperty));
                tbPassword.ToolTip = null;
            }
            tbPasswordShowed.Text = tbPassword.Password;
        }

        private void BtnKeyCiClick(object sender, RoutedEventArgs e)
        {
            var grantPermission = new GrantDirectorPermissionWindows();
            if (grantPermission.ShowDialog() == true)
            {
                tbCI.IsEnabled = true;
            }
        }

        private void tbPasswordShowed_TextChanged(object sender, TextChangedEventArgs e)
        {
        }
    }
}
